package com.yimaxiaoerlang.socket;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;

public class IMWbeSocketClient extends WebSocketClient {
    private final String TAG = IMWbeSocketClient.class.getSimpleName();
    private final int HEARTBEAT_MESSAGE_TAG = 1;
    private final int RESTART_CONNECT_TAG = 2;
    private final String HEARTBEAT_MESSAGE = "1";
    private boolean userClose = false;
    private ClientStateListener listener;

    public IMWbeSocketClient(URI serverUri, Draft draft) {
        super(serverUri, draft);
    }

    public IMWbeSocketClient(URI serverURI) {
        super(serverURI);
    }


    /**
     * 链接
     */
    @Override
    public void connect() {
        super.connect();
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        Log.e(TAG, "链接成功");
        startHeartbeat();
        if (listener != null) {
            listener.onConnected();
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {//链接断开
//        -1链接失败
        System.out.println("closed with exit code " + code + " additional info: " + reason);
        Log.e(TAG, "onClose: " + "closed with exit code " + code + " additional info: " + reason);

        if (code == 1002) {//token错误
            Log.d(TAG, "Token 错误");
            if (listener != null) {
                listener.authenticationError();
            }
            return;
        }

        stopHeartbeat();
        if (listener != null) {
            listener.onDisconnected();
        }

        if (!userClose && !isOpen()) {//不是用户关闭重新链接
            Log.d(TAG, "不是用户主动关闭的连接，进行重新链接");
            restartConnect();
        }

    }

    @Override
    public void onMessage(String message) {
//        System.out.println("received message: " + message);
        if (message == null)
            return;
        System.out.println("received message[Soc]: " + message);
        String receiveMessage = message.toString();
        if (receiveMessage.trim().equals(HEARTBEAT_MESSAGE)) {
            Log.d(TAG, "收到心跳回复消息[Soc]" + message);
        } else {
            Log.e(TAG, "收到消息[Soc]" + message);
            if (listener != null) {
                listener.onReceiveMessage(message);
            }
        }
    }

    @Override
    public void onMessage(ByteBuffer message) {
        System.out.println("received ByteBuffer");
    }

    @Override
    public void onError(Exception ex) {//发生错误
        System.err.println("an error occurred:" + ex);

        if (!isOpen()) {
            restartConnect();
        }
    }

    /**
     * 开始定时发送心跳
     */
    private void startHeartbeat() {
        Log.e(TAG, "开始心跳");
        if (!handler.hasMessages(HEARTBEAT_MESSAGE_TAG)) {
            handler.sendEmptyMessage(HEARTBEAT_MESSAGE_TAG);
        }

    }

    /**
     * 结束发送心跳
     */
    private void stopHeartbeat() {
        if (handler.hasMessages(HEARTBEAT_MESSAGE_TAG)) {
            Log.e(TAG, "结束心跳");
            handler.removeMessages(HEARTBEAT_MESSAGE_TAG);
        }
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            if (msg.what == HEARTBEAT_MESSAGE_TAG) {//心跳
                if (isOpen()) {
                    Log.d(TAG, "发送心跳");
                    IMWbeSocketClient.this.sendMessage(HEARTBEAT_MESSAGE);
                    sendEmptyMessageDelayed(HEARTBEAT_MESSAGE_TAG, 10000);
                }

            } else if (msg.what == RESTART_CONNECT_TAG) {//重连
                Log.d(TAG, "重新连接");
                reconnect();
            }

        }
    };

    /**
     * 发送消息
     *
     * @param msg
     */
    private void sendMessage(String msg) {
        if (getConnection().isOpen() && !handler.hasMessages(HEARTBEAT_MESSAGE_TAG)) {
            send(msg);
        }

    }

    /**
     * 重新连接
     */
    private void restartConnect() {
        if (!handler.hasMessages(RESTART_CONNECT_TAG)) {
            Log.e(TAG, "restartConnect: 重新连接");
            //两秒后重新链接
            handler.sendEmptyMessageDelayed(RESTART_CONNECT_TAG, 5000);
        }
    }


    /**
     * 关闭重连
     */
    private void stopRestartConnect() {
        if (handler.hasMessages(RESTART_CONNECT_TAG)) {
            handler.removeMessages(RESTART_CONNECT_TAG);

        }
    }

    /**
     * 断开连接
     */
    public void closeConnect() {
        Log.e(TAG, "关闭链接");
        stopRestartConnect();
        userClose = true;
        close();
    }

    public void setStateListener(ClientStateListener listener) {
        this.listener = listener;
    }
}
